package com.huike.report.demo;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CompletableFutureDemo {
    /*public static void main(String[] args) {

        //如果是runAsync方法，则不需要return
        CompletableFuture completableFuture = CompletableFuture.supplyAsync(()->{
            log.info("执行线程-----开始----");
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                log.info("执行线程-----处理数据中----无操作--无返回--");
                log.info("执行线程-----结束----");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new Result("飞翔的咩咩","1");
        });
        //需要返回结果
        CompletableFuture completableFutureA = CompletableFuture.supplyAsync(()->{
            log.info("执行线程A-----开始----");
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                log.info("执行线程A-----处理数据中-----");
                log.info("执行线程A-----结束----");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new Result("飞翔的咩咩A","25");
        });
        //需要返回结果
        CompletableFuture completableFutureB = CompletableFuture.supplyAsync(()->{
            log.info("执行线程B-----开始----");
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                log.info("执行线程B-----数据处理中:----");
                log.info("执行线程B-----结束----");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new Result("飞翔的咩咩B","25");
        });
        //C会等待A和B结束后执行。
        CompletableFuture completableFutureC = completableFutureA.thenCombine(completableFutureB,(resultA,resultB)->{
            log.info("执行线程保存处理结果-----开始----");
            List<Result> resultList = new ArrayList<Result>();
            Result rsA = (Result) resultA;
            Result rsB = (Result) resultB;
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                rsA.setAge(String.valueOf(Integer.parseInt(rsA.getAge())+1));
                rsB.setAge(String.valueOf(Integer.parseInt(rsB.getAge())+1));
                log.info("执行线程保存处理结果-----resultA,age+1后为:{}----",rsA.toString());
                log.info("执行线程保存处理结果-----resultB,age+1后为:{}----",rsB.toString());
                resultList.add(rsA);
                resultList.add(rsB);
                log.info("执行线程保存处理结果-----结束----");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return resultList;
        });

        System.out.println(completableFutureC.join());


    }*/
}